﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CodeBox.Development.Tools.Foundation.Interfaces;
using System.ComponentModel.Composition;
using CodeBox.Development.Tools.Foundation.Extensions;
using System.IO;
using CodeBox.Development.Tools.RepositoryBuilder.Engine.Interfaces;

namespace CodeBox.Development.Tools.RepositoryBuilder.Extensions
{
    /// <summary>
    /// A <see cref="IDirectoryStructureBuilder"/> implementation for a directory structure based on the Subversion repository. 
    /// </summary>
    [Export(typeof(IDirectoryStructureBuilder))]
    [ExportProperty("Name", "SVNStyleFolderStructureBuilder")]
    [ExportProperty("Description", "Build a directory structure based on the Subversion repository.")]
    public class SVNStyleFolderStructureBuilder : IDirectoryStructureBuilder
    {
        #region IDirectoryStructureBuilder Members
        /// <summary>
        /// Gets or sets the path of the root directory.
        /// </summary>
        public string RootDirectory { get;set; }

        /// <summary>
        /// Gets or sets the name of the project.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Build a directory structure based on the Subversion repository. 
        /// </summary>
        /// <returns><see cref="true"/> if structure created; otherwise <see cref="false"/>.</returns>
        public bool Execute()
        {
            if (RootDirectory.IsNullOrEmpty())
            {
                throw new ArgumentNullException("StartUpDirectory");
            }
            else
            {
                if (!Directory.Exists(RootDirectory))
                {
                    throw new DirectoryNotFoundException(RootDirectory);
                }
            }

            string projectPath = Path.Combine(RootDirectory, Name);
            CreateDirectory(RootDirectory, Name);

            CreateDirectory(projectPath, "branches");
            CreateDirectory(projectPath, "tags");
            CreateDirectory(projectPath, "trunk");
            return true;
        }
        #endregion

        #region CreateDirectory
        /// <summary>
        /// Creates a directory based on the start up path and the new directory name.
        /// </summary>
        /// <param name="startUpDirectory">Root of the new directory.</param>
        /// <param name="directoryName">Name of the new directory.</param>
        private void CreateDirectory(string startUpDirectory, string directoryName)
        {
            string directoryPath = Path.Combine(startUpDirectory, directoryName);
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
        }
        #endregion
    }
}
